import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters, mixins

from can_i_leave.utils import AskForLeave
from forleave.models import StudentGroup, StudentInfo, ForLeaveRecord
from forleave.paginations import CommonPagination
from forleave.serializers import StudentGroupSerializer, StudentInfoSerializer, ForLeaveRecordSerializer


class StudentInfoViewSet(viewsets.ModelViewSet):
    """
        学生信息
    """

    queryset = StudentInfo.objects.all()
    serializer_class = StudentInfoSerializer
    pagination_class = CommonPagination
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name', 'username')


class StudentGroupViewSet(viewsets.ModelViewSet):
    """
        学生群组
    """

    queryset = StudentGroup.objects.all()
    serializer_class = StudentGroupSerializer
    pagination_class = CommonPagination
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name',)


class DefaultGroupView(View):
    """
        设置默认分组
    """

    def post(self, request):
        try:
            data = json.loads(request.body)
            task_type = data.get('type', None)
            group_id = data.get('id', -1)
            for group in StudentGroup.objects.all():
                group.is_default = False
                group.save()

            # 设置默认组
            if task_type == 1:
                try:
                    target_group = StudentGroup.objects.get(id=group_id)
                    target_group.is_default = True
                    target_group.save()
                except StudentGroup.DoesNotExist as e:
                    pass
            # 取消默认组
            elif task_type == 0:
                try:
                    target_group = StudentGroup.objects.get(id=group_id)
                    target_group.is_default = False
                    target_group.save()
                except StudentGroup.DoesNotExist as e:
                    pass

        except Exception as e:
            print(e)
            return JsonResponse({'status': 'Failed'})

        return JsonResponse({'status': 'OK'})


class ForLeaveView(View):
    def get(self, request):
        return JsonResponse({})

    def post(self, request):
        try:
            data = json.loads(request.body)
            if 'type' not in data.keys() or 'ids' not in data.keys():
                return JsonResponse({
                    'status': 'Failed'
                })

            # 查询学生信息
            task_type = data.get('type', -1)
            ids = data.get('ids', [])
            students = []
            groups = None

            # type：0 表示默认分组，type：1 ids表示学生id，type：2 ids表示群组的id
            if task_type == 0:
                groups = StudentGroup.objects.filter(is_default=True)
            elif task_type == 1:
                students = StudentInfo.objects.filter(pk__in=ids)
            elif task_type == 2:
                groups = StudentGroup.objects.filter(pk__in=ids)

            if groups and len(groups) > 0:
                for group in groups:
                    students.extend(group.students.all())

            # 去重
            students = set(students)
            # 执行异步任务
            for student in students:
                ask_for_leave = AskForLeave(student)
                ask_for_leave.start()

        except Exception as e:
            print(e)
            return JsonResponse({
                'status': 'Failed'
            })

        return JsonResponse({
            'status': 'OK'
        })


class ForLeaveRecordViewSet(viewsets.GenericViewSet,
                            mixins.ListModelMixin,
                            mixins.RetrieveModelMixin):
    """
        请假记录
    """
    queryset = ForLeaveRecord.objects.all()
    serializer_class = ForLeaveRecordSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('student__id',)
    # search_fields = ('name',)
